package edu.uwm.univesitydb.mock;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import edu.uwm.universitydb.swing.DataTableModel;

public class MockUserService extends DataTableModel{
	
	public MockUserService() {
		super(_colNames, _colTypes);
	}
	
	public boolean addUser(String name, String password, Role role) {
		return _users.add(new User(name, role));
	}
	
	public boolean updateUser(String name, Role role) {
		User usr = getUserByID(name);
		if(usr != null) {
			usr._name = name;
			usr._role = role;
			return true;
		} else {
			return false;
		}
	}
	
	public boolean deleteByID(String id) {
		User match = null;
		for(User usr: _users) {
			if(usr._name.equals(id)) {
				match = usr;
				break;
			}
		}
		return (match == null) ? false : _users.remove(match);
	}

	
	public String getNameByID(String id) {
		User usr = getUserByID(id);
		if (usr != null) {
			return usr._name;
		} else {
			return "";
		}
	}
	
	public Role getRoleByID(String id) {
		User usr = getUserByID(id);
		if (usr != null) {
			return usr._role;
		} else {
			return null;
		}
	}
	
	public Role getRoleByID(int id) {
		for (Role role : _roles) {
			if (role._id == id) {
				return role;
			}
		}
		return null;
	}

	private User getUserByID(String name) {
		for (User usr : _users) {
			if (usr._name.equals(name)) {
				return usr;
			}
		}
		return null;
	}
	
	@Override
	public int getRowCount() {
		return _users.size();
	}
	
	@Override
	public Object getValueAt(int row, int col) {
		switch (col) {
		case 0:
			return _users.get(row)._name;
		case 1:
			return _users.get(row)._role._name;
		default:
			return "Error";
		}
	}
	
	public Role[] getRoles() {
		return _roles.toArray(new Role[_roles.size()]);
	}

	public static class Role {
		public int _id;
		public String _name;
		
		public Role(int id, String name) {
			_id = id;
			_name = name;
		}
		public String toString() {
			return _name;
		}
		public boolean equals(Object o) {
			return (o instanceof Role && ((Role)o)._id == this._id);
		}
	}
	
	public static class User {
		public Role _role;
		public String _name;
		
		public User(String name, Role role) {
			_role = role;
			_name = name;
		}
	}
	
	private static List<Role> _roles = Arrays.asList(new Role[] {
			new Role(1,"Administrator"),
			new Role(2,"Professor")
	});
	private static List<User> _users = new ArrayList<User>(Arrays.asList(new User[] {
			new User("admin", _roles.get(0)),
			new User("Jon", _roles.get(1)),
			new User("Shyam", _roles.get(1)),
			new User("Jose", _roles.get(1)),
	}));

	private static final String[] _colNames = new String[] {"User","Role"};
	private static final Class<?>[] _colTypes = new Class<?>[] {String.class, Role.class};
	
	private static final long serialVersionUID = -8896649559972624086L;

}
